package stack_queue.stack;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

//基于数组的栈实现
public class MyStack <E>{
//    当前栈的个数
    private int size;
//    建立一个动态数组存放数据
    private List<E> data = new ArrayList<>();

    /**
     * 入栈方法
     * @param val  入栈的值
     */
    public void push(E val){
        data.add(val);  //默认尾插
        size++;
    }

    /**
     * 出栈
     */
    public E pop(){
        if(isEmpty()){
           throw new NoSuchElementException(" stack is empty. Can't pop val");
        }
        E val = data.remove(size-1);
        size--;
        return val;
    }

    /**
     * 返回栈顶元素
     * @return   返回栈顶的值
     */
    public E peek(){
        if (isEmpty()){
            throw new NoSuchElementException("stack is empty. Can't pop val");
            }
        return data.get(size - 1);
    }

    public boolean isEmpty(){
        return size-1 == 0;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < size; i++) {
            sb.append(data.get(i));
            //没有到栈顶
            if (i != size - 1){
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
